//
//  ChatViewController.m
//  Findif
//
//  Created by Cicel Chen on 2018/10/18.
//  Copyright © 2018年 Cicel Chen. All rights reserved.
//

#import "ChatViewController.h"
#import "ChatListTableViewCell.h"
#import "ChatRoomViewController.h"
#import <JMessage/JMessage.h>
//#import <Photos/Photos.h>
//#import "MessageModel.h"
//#import "UserModel.h"
//#import "MessageEventCollectionViewCell.h"
//#import "MessageEventModel.h"
#import "ContactsHeaderView.h"
#import "ContactsTableViewHeaderView.h"
#import "SearchContactsViewController.h"
#import "MyAttentionTableViewCell.h"
#import "MyFansTableViewCell.h"
#import "MyAttentionModel.h"
#import "addContactsViewController.h"
#import "GroupModel.h"
#import "AddGroupTableViewCell.h"
#import "GroupInfoViewController.h"
#import "MessageNotiModel.h"
#import "GroupNotiViewController.h"


@interface ChatViewController ()<UITableViewDelegate,UITableViewDataSource,ContactsHeaderViewDelegate,MyAttentionTableViewCellDelegate,MyFansTableViewCellDelegate,JMessageDelegate>

@property (nonatomic, weak)UITableView * messageTableView;
@property (nonatomic, weak)UITableView * contactsTableView;
@property (nonatomic, strong)NSMutableArray * meaasgeArray;
@property (nonatomic, strong)UIButton * messageButton;
@property (nonatomic, strong)UIButton * contactsButton;
@property (nonatomic, strong)UIView * messageLineView;
@property (nonatomic, strong)UIView * contactsLineView;
@property (nonatomic, weak)UIButton * addButton;
@property (nonatomic, strong)NSArray<MyAttentionModel *> * attentionArray;
@property (nonatomic, strong)NSArray<MyAttentionModel *> * fansArray;
@property (nonatomic, strong)NSArray<GroupModel *> * groupArray;
@property (nonatomic, strong)NSArray<MessageNotiModel *> * notiArray;
@property (strong, nonatomic) NSMutableArray *dataArray;
@property (strong, nonatomic) NSMutableDictionary *dataDic;
@property (nonatomic, copy)NSString * unreadCount;


@end

@implementation ChatViewController

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self loadData];
    [self getConversationList];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = ZRWhiteColor;
    self.meaasgeArray = [NSMutableArray array];
    self.dataArray = [NSMutableArray array];
    self.dataDic = [NSMutableDictionary dictionary];
    self.groupArray = [NSArray array];
    self.attentionArray = [NSArray array];
    self.fansArray = [NSArray array];
    
    
    [self setupNav];
    [self setupUI];
    [self addDelegate];
}

#pragma mark --add Delegate
- (void)addDelegate {
//    [JMessage addDelegate:self withConversation:self.conversation];
    [JMessage addDelegate:self withConversation:nil];
}

- (void)loadData{
    
    NSString * user_id = DEF_GET_OBJECT(@"id");
    [self.dataArray removeAllObjects];
    [self.dataDic removeAllObjects];
    [[ZRNetworkTool sharedTool] getAttentionUserUser_id:user_id WithSearch:@"" ResultWithBlock:^(BOOL success, id responseData) {
        
        
        if (success) {
            
            self.attentionArray = [NSArray yy_modelArrayWithClass:[MyAttentionModel class] json:responseData[@"data"]];
            
            [self.dataArray addObject:self.attentionArray];
        }else{
            
            [self.dataArray addObject:self.attentionArray];
        }
    }];

    [[ZRNetworkTool sharedTool] getFansUserUser_id:user_id WithSearch:@"" ResultWithBlock:^(BOOL success, id responseData) {
        
//        NSLog(@"model===%@",responseData);
        if (success) {
            
            self.fansArray = [NSArray yy_modelArrayWithClass:[MyAttentionModel class] json:responseData[@"data"]];
            
            [self.dataArray addObject:self.fansArray];
        }else{
            
            [self.dataArray addObject:self.fansArray];
        }
    }];
    
    [[ZRNetworkTool sharedTool] getUserGroupListWithUser_idt:user_id WithBlock:^(BOOL success, id responseData) {

//        NSLog(@"res===%@",responseData);
        
        if (success) {
            
            self.groupArray = [NSArray yy_modelArrayWithClass:[GroupModel class] json:responseData[@"data"]];
            
            [self.dataArray addObject:self.groupArray];
        }else{
            
            [self.dataArray addObject:self.groupArray];
        }
    }];

    [self.contactsTableView.mj_header endRefreshing];
}


- (void)setDataArray:(NSMutableArray *)dataArray{
    
    _dataArray = dataArray;
    
    [self.contactsTableView reloadData];
}

- (void)setNotiArray:(NSArray<MessageNotiModel *> *)notiArray{
    
    _notiArray = notiArray;
    
    [self.messageTableView reloadData];
}

- (void)setAttentionArray:(NSArray<MyAttentionModel *> *)attentionArray{
    
    _attentionArray = attentionArray;
    
    [self.contactsTableView reloadData];
}


- (void)setFansArray:(NSArray<MyAttentionModel *> *)fansArray{
    
    _fansArray = fansArray;
    
    [self.contactsTableView reloadData];
}


- (void)setGroupArray:(NSArray<GroupModel *> *)groupArray{
    
    _groupArray = groupArray;
    
    [self.contactsTableView reloadData];
}

- (void)setUnreadCount:(NSString *)unreadCount{
    
    _unreadCount = unreadCount;
    
    [self.messageTableView reloadData];
}

- (void)setupNav{
    
    self.messageButton = [self setupButtonWithTitle:@"消息"];
    self.messageButton.selected = YES;
    [self.view addSubview:self.messageButton];
    self.contactsButton = [self setupButtonWithTitle:@"联系人"];
    [self.view addSubview:self.contactsButton];
    
    self.messageLineView = [self setupLineView];
    self.messageLineView.hidden = NO;
    [self.view addSubview:self.messageLineView];
    self.contactsLineView = [self setupLineView];
    [self.view addSubview:self.contactsLineView];
    
    
    UIButton * addButton = [[UIButton alloc] init];
    
    [addButton setImage:[UIImage imageNamed:@"add"] forState:UIControlStateNormal];
    [addButton addTarget:self action:@selector(clickAddButton) forControlEvents:UIControlEventTouchUpInside];
    addButton.hidden = YES;
    
    self.addButton = addButton;
    
    [self.view addSubview:self.addButton];
}


- (void)setupUI{
    
    UITableView * messageTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, topHeight, kScreenW, kScreenH - topHeight - kTabBarHeight) style:UITableViewStylePlain];
    messageTableView.delegate = self;
    messageTableView.dataSource = self;
    messageTableView.backgroundColor = ColorWithRGB(0xEFF0F1);
    messageTableView.rowHeight = 90 * SCREENH6;
    messageTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    messageTableView.showsVerticalScrollIndicator = NO;
    
    self.messageTableView = messageTableView;
    
    [self.messageTableView registerClass:[ChatListTableViewCell class] forCellReuseIdentifier:@"ChatListTableViewCell"];
    
    self.messageTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        
        [self getConversationList];
    }];
    
    [self.view addSubview:self.messageTableView];

    UITableView * contactsTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, topHeight, kScreenW, kScreenH - topHeight - kTabBarHeight) style:UITableViewStylePlain];
    contactsTableView.delegate = self;
    contactsTableView.dataSource = self;
    contactsTableView.backgroundColor = ColorWithRGB(0xEFF0F1);
    contactsTableView.rowHeight = 60 * SCREENH6;
    contactsTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    contactsTableView.showsVerticalScrollIndicator = NO;
    contactsTableView.hidden = YES;
    
    ContactsHeaderView * headerView =  [[ContactsHeaderView alloc] initWithFrame:CGRectMake(0, 0, kScreenW, 50 * SCREENH6)];
    headerView.delegate = self;
    // 设置header
    contactsTableView.tableHeaderView = headerView;
    
    self.contactsTableView = contactsTableView;
    
    
    [self.contactsTableView registerClass:[AddGroupTableViewCell class] forCellReuseIdentifier:@"ChatAddGroupTableViewCell"];
    [self.contactsTableView registerClass:[MyAttentionTableViewCell class] forCellReuseIdentifier:@"ChatMyAttentionTableViewCell"];
    [self.contactsTableView registerClass:[MyFansTableViewCell class] forCellReuseIdentifier:@"ChatMyFansTableViewCell"];
    [self.contactsTableView registerClass:[ContactsTableViewHeaderView class] forHeaderFooterViewReuseIdentifier:@"ContactsTableViewHeaderView"];
    
    self.contactsTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

        [self loadData];
    }];
    
    [self.view addSubview:self.contactsTableView];
}


- (void)viewDidLayoutSubviews{
    
    [self.messageButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.view).offset(115 * SCREENH6);
        make.top.mas_equalTo(self.view).offset(kStatusBarHeight + 10 * SCREENH6);
        make.width.mas_equalTo(35 * SCREENH6);
        make.height.mas_equalTo(16 * SCREENH6);
    }];
    
    [self.messageLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.messageButton);
        make.top.mas_equalTo(self.messageButton.mas_bottom).offset(10 * SCREENH6);
        make.height.mas_equalTo(1 * SCREENH6);
    }];
    
    [self.contactsButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(self.messageButton.mas_trailing).offset(75 * SCREENH6);
        make.top.mas_equalTo(self.view).offset(kStatusBarHeight + 10 * SCREENH6);
        make.width.mas_equalTo(50 * SCREENH6);
        make.height.mas_equalTo(16 * SCREENH6);
    }];
    
    [self.contactsLineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.mas_equalTo(self.contactsButton);
        make.top.mas_equalTo(self.contactsButton.mas_bottom).offset(10 * SCREENH6);
        make.height.mas_equalTo(1.5 * SCREENH6);
    }];
    
    [self.addButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.trailing.mas_equalTo(self.view).offset(-15 * SCREENH6);
        make.centerY.mas_equalTo(self.contactsButton);
        make.width.height.mas_equalTo(30 * SCREENH6);
    }];
}


- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    
    if (tableView == self.messageTableView) {
        
        return 1;
    }else{
        
        return 3;
    }
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (tableView == self.messageTableView) {
        
        return self.meaasgeArray.count + 1;
    }else{
        
        // 取出字典中的 section 如果是第 0 个分区 那么就返回该分区的数据
        if ([[self.dataDic valueForKey:[NSString stringWithFormat:@"%ld",section]] isEqualToString:@"0"])
        {
            return [self.dataArray[section] count];
        }else
        {
//            NSLog(@"**************");
            return 0;
        }
        
    }
    
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (tableView == self.messageTableView) {
        
//        ChatListTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatListTableViewCell" forIndexPath:indexPath];
        ChatListTableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath]; //根据indexPath准确地取出一行，而不是从cell重用队列中取出
        if (cell == nil) {
            cell = [[ChatListTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"ChatListTableViewCell"];
            
        }
        
        if (indexPath.row == 0) {
           
            cell.model = self.notiArray.firstObject;
            cell.unreadCount = self.unreadCount;
            
        }else{
            
            JMSGConversation *conversation = self.meaasgeArray[indexPath.row - 1];
            
            cell.conversation = conversation;
        }
        
        
        return cell;
    }else{
        
        if(indexPath.section == 0){
            
            MyAttentionTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatMyAttentionTableViewCell" forIndexPath:indexPath];
            
            if (indexPath.row >= self.attentionArray.count) {
                
                cell.model = self.attentionArray[indexPath.row - 1];
            }else{
                
                cell.model = self.attentionArray[indexPath.row];
            }
            cell.model = self.attentionArray[indexPath.row];
            cell.delegate = self;
            
            return cell;
        }else if(indexPath.section == 1){
            
            MyFansTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatMyFansTableViewCell" forIndexPath:indexPath];
            
            
            if (indexPath.row >= self.fansArray.count) {
                
                cell.model = self.fansArray[indexPath.row - 1];
            }else{
                
                cell.model = self.fansArray[indexPath.row];
            }
            
            cell.delegate = self;
            
            return cell;
        }else{
            
            AddGroupTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ChatAddGroupTableViewCell" forIndexPath:indexPath];
            
            if (indexPath.row >= self.groupArray.count) {
                
                cell.model = self.groupArray[indexPath.row - 1];
            }else{
                
                cell.model = self.groupArray[indexPath.row];
            }
//            cell.model = self.groupArray[indexPath.row];
            
            return cell;
        }
        
    }
}


- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    
    if (tableView == self.contactsTableView) {
        
        return 50 * SCREENH6;
    }else{
        
        return 0;
    }
    
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    if (tableView == self.contactsTableView) {
        
        ContactsTableViewHeaderView * header = [tableView dequeueReusableHeaderFooterViewWithIdentifier:@"ContactsTableViewHeaderView"];
        
        header.userInteractionEnabled = YES;
        header.tag = section;
        UITapGestureRecognizer *tapGR = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        
        [header addGestureRecognizer:tapGR];
        
        switch (section) {
            case 0:
                header.titleLabel.text = @"我的关注";
                header.countLabel.text = [NSString stringWithFormat:@"%lu",self.attentionArray.count];
                break;
            case 1:
                header.titleLabel.text = @"我的粉丝";
                header.countLabel.text = [NSString stringWithFormat:@"%lu",self.fansArray.count];
                break;
            case 2:
                header.titleLabel.text = @"我的群组";
                header.countLabel.text = [NSString stringWithFormat:@"%lu",self.groupArray.count];
                break;
            default:
                break;
        }
        
        return header;
    }else{
        
        return nil;
    }   
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    
    if (tableView == self.messageTableView) {
        
        HiddenBar;
        
        if (indexPath.row == 0) {
            
            GroupNotiViewController * notiVC = [GroupNotiViewController new];
            
            [self.navigationController pushViewController:notiVC animated:YES];

        }else{
            
            ChatRoomViewController * roomVC = [ChatRoomViewController new];
            
            JMSGConversation * conversation = self.meaasgeArray[indexPath.row - 1];
            
//            NSLog(@"conversation===%@",conversation);
            
            if (conversation.conversationType == 1) {
                //单聊
                roomVC.conversation = conversation;
                
                [self.navigationController pushViewController:roomVC animated:YES];
                
            }else if (conversation.conversationType == 2){
                //群聊
                JMSGGroup * group = conversation.target;

                 NSDictionary * dict = @{@"group_jg_gid":group.gid};
                
                 [[ZRNetworkTool sharedTool] checkGroupStatusWithDict:dict WithBlock:^(BOOL success, id responseData) {
                    
                    if (success) {
                        
                        roomVC.conversation = conversation;
                        roomVC.group_jg_gid = group.gid;
                        
                        [self.navigationController pushViewController:roomVC animated:YES];
                    }else{
                        
                        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                                       message:responseData[@"message"]
                                                                                preferredStyle:UIAlertControllerStyleAlert];
                        
                        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                              handler:^(UIAlertAction * action) {
                                                                                  [JMSGConversation deleteGroupConversationWithGroupId:group.gid];
                                                                                  
                                                                                  [self getConversationList];
                                                                              }];
                        
                        [alert addAction:defaultAction];
                        [self presentViewController:alert animated:YES completion:nil];
                    }
                    
                }];
            }
        }
     
        ShowBar;
    }else{
        
        if (indexPath.section == 2) {
            
            HiddenBar;

            AddGroupTableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
            
            GroupModel * model = cell.model;
       
            [JMSGConversation createGroupConversationWithGroupId:cell.model.group_jg_gid completionHandler:^(id resultObject, NSError *error) {
                
                if (error == nil) {
                    
                    ChatRoomViewController * roomVC = [ChatRoomViewController new];
                    
                    roomVC.conversation = resultObject;
                    roomVC.group_jg_gid = model.group_jg_gid;
                    
                    [self.navigationController pushViewController:roomVC animated:YES];
                    
                } else {
                    
                    
                }
            }];
            
            ShowBar;
        }else if (indexPath.section == 0){
            
            MyAttentionTableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
            NSString * phone = [NSString stringWithFormat:@"%@",cell.model.attention_user_phone];
            
            [JMSGConversation createSingleConversationWithUsername:phone completionHandler:^(id resultObject, NSError *error) {
                
                if (error == nil) {
                    HiddenBar;
                    ChatRoomViewController * roomVC = [ChatRoomViewController new];
                    
                    roomVC.conversation = resultObject;
                    
                    [self.navigationController pushViewController:roomVC animated:YES];
                    
                    ShowBar;
                } else {
                    
                }
            }];
        }else if (indexPath.section == 1){
            
            MyFansTableViewCell * cell = [tableView cellForRowAtIndexPath:indexPath];
            NSString * phone = [NSString stringWithFormat:@"%@",cell.model.attention_user_phone];
            
            [JMSGConversation createSingleConversationWithUsername:phone completionHandler:^(id resultObject, NSError *error) {
                
                if (error == nil) {
                    HiddenBar;
                    ChatRoomViewController * roomVC = [ChatRoomViewController new];
                    
                    roomVC.conversation = resultObject;
                    
                    [self.navigationController pushViewController:roomVC animated:YES];
                    
                    ShowBar;
                } else {
                    
                }
            }];
        }
    }
}


- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section{
    
    if (tableView == self.contactsTableView) {
        
        if ([view isKindOfClass:[UITableViewHeaderFooterView class]]) {
            ((UITableViewHeaderFooterView *)view).backgroundView.backgroundColor = ZRWhiteColor;
        }
    } 
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    //第二组可以左滑删除
    if (tableView == self.messageTableView) {
        
        if (indexPath.row == 0) {
            
            return NO;
        }
        return YES;
    }
    
    return NO;
}

// 定义编辑样式
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return UITableViewCellEditingStyleDelete;
}

// 进入编辑模式，按下出现的编辑按钮后,进行删除操作
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        
        if (tableView == self.messageTableView) {
            
            JMSGConversation *conversation = self.meaasgeArray[indexPath.row - 1];

            if (conversation.conversationType == 1) {
                //单聊
                JMSGUser *user = conversation.target;
//                deleteSingleConversationWithUsername:(NSString *)username
                [JMSGConversation deleteSingleConversationWithUsername:user.username];
                
                [self getConversationList];
            }else if (conversation.conversationType == 2){
               //群聊
                JMSGGroup * group = conversation.target;
                
                [JMSGConversation deleteGroupConversationWithGroupId:group.gid];
                
                [self getConversationList];
            }
        }
    }
}

// 修改编辑按钮文字
- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return @"删除";
}


- (void)getConversationList {
    
    [JMSGConversation allConversations:^(id resultObject, NSError *error) {

        if (!error) {
            
            self.meaasgeArray = [self sortConversation:resultObject];
            
            [self.messageTableView reloadData];
        }else if (error.code == 863004){
            
            if (DEF_GET_OBJECT(@"phone")) {
               
                NSString * phone = DEF_GET_OBJECT(@"phone");
                
                [JMSGUser loginWithUsername:phone password:phone completionHandler:^(id resultObject, NSError *error) {
                    
                    if (error == nil) {
                        
                        [JMSGConversation allConversations:^(id resultObject, NSError *error) {
                            
                            self.meaasgeArray = [self sortConversation:resultObject];
                            
                            [self.messageTableView reloadData];
                        }];
                    }else{
                        
                        
                    }
                }];
            }

        }
        
    }];
    
    NSString * user_id = DEF_GET_OBJECT(@"id");
    
    [[ZRNetworkTool sharedTool] getGroupInformWithUser_id:user_id WithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
            NSDictionary * dict = responseData[@"data"];
            self.notiArray = [NSArray yy_modelArrayWithClass:[MessageNotiModel class] json:dict[@"dataArr"]];
            self.unreadCount = [NSString stringWithFormat:@"%@",dict[@"unreadCount"]];
        }
    }];
    
    [self.messageTableView.mj_header endRefreshing];
}


#pragma mark --排序conversation
- (NSMutableArray *)sortConversation:(NSMutableArray *)conversationArr {
    NSSortDescriptor *firstDescriptor = [[NSSortDescriptor alloc] initWithKey:@"latestMessage.timestamp" ascending:NO];
    
    NSArray *sortDescriptors = [NSArray arrayWithObjects:firstDescriptor, nil];
    
    NSArray *sortedArray = [conversationArr sortedArrayUsingDescriptors:sortDescriptors];
    
    return [NSMutableArray arrayWithArray:sortedArray];
}


- (void)updateData{
    
    [JMSGConversation allConversations:^(id resultObject, NSError *error) {
        
        self.meaasgeArray = [self sortConversation:resultObject];
        
        [self.messageTableView reloadData];
    }];
    
    [self.messageTableView.mj_header endRefreshing];
}


- (UIView *)setupLineView{
    
    UIView * lineView = [UIView new];
    
    lineView.backgroundColor = ColorWithRGB(0xFFD733);
    lineView.hidden = YES;
    
    return lineView;
}


- (UIButton *)setupButtonWithTitle:(NSString *)title{
    
    UIButton * button = [UIButton new];
    
    [button setTitle:title forState:UIControlStateNormal];
    [button setTitleColor:ZRBlackColor forState:UIControlStateSelected];
    [button setTitleColor:ColorWithRGB(0x909090) forState:UIControlStateNormal];
    [button addTarget:self action:@selector(cilckNavButton:) forControlEvents:UIControlEventTouchUpInside];
    button.titleLabel.font = [UIFont systemFontOfSize:16 * SCREENH6];
    
    return button;
}


- (void)tapAction:(UITapGestureRecognizer*)sender{
    
    ContactsTableViewHeaderView * header = (ContactsTableViewHeaderView *)sender.view;
    
//    header.statusImageView.image = [UIImage imageNamed:@"多边形下"];
    NSInteger temp = header.tag;
    
    if ([header.status isEqualToString:@"show"]) {

        header.status = @"hidden";
    }else if ([header.status isEqualToString:@"hidden"]){

        header.status = @"show";
    }
//
//    NSLog(@"temp==%ld",temp);
    // 修改 每个区的收缩状态  因为每次点击后对应的状态改变 temp代表是哪个section
    if ([[self.dataDic valueForKey:[NSString stringWithFormat:@"%ld",temp]]isEqualToString:@"0"] )
    {
        [self.dataDic setObject:@"1" forKey:[NSString stringWithFormat:@"%ld",temp]];
    }else
    {
        [self.dataDic setObject:@"0" forKey:[NSString stringWithFormat:@"%ld",temp]];
    }

    if (temp == 0) {

        if (self.attentionArray.count > 0) {
            // 更新 section
            [self.contactsTableView reloadSections:[NSIndexSet indexSetWithIndex:temp] withRowAnimation:(UITableViewRowAnimationFade)];
        }
    }else if (temp == 1){

        if (self.fansArray.count > 0) {
            // 更新 section
            [self.contactsTableView reloadSections:[NSIndexSet indexSetWithIndex:temp] withRowAnimation:(UITableViewRowAnimationFade)];
        }
    }else if (temp == 2){

        if (self.groupArray.count > 0) {
            // 更新 section
            [self.contactsTableView reloadSections:[NSIndexSet indexSetWithIndex:temp] withRowAnimation:(UITableViewRowAnimationFade)];
        }
    }
}


- (void)cilckNavButton:(UIButton *)button{
    
    if (button == self.messageButton) {
        
        if (!button.selected) {
            
            button.selected = YES;
            
            self.messageLineView.hidden = NO;
            self.contactsButton.selected = NO;
            self.contactsLineView.hidden = YES;
            self.addButton.hidden = YES;
            self.messageTableView.hidden = NO;
            self.contactsTableView.hidden = YES;
        }
    }else{
        
        if (!button.selected) {
            
            button.selected = YES;
            
            self.contactsLineView.hidden = NO;
            self.messageButton.selected = NO;
            self.messageLineView.hidden = YES;
            self.addButton.hidden = NO;
            self.messageTableView.hidden = YES;
            self.contactsTableView.hidden = NO;
        }
    }
}


- (void)clickAddButton{
    
    HiddenBar;
    addContactsViewController * addVC = [addContactsViewController new];
    
    [self.navigationController pushViewController:addVC animated:YES];
    ShowBar;
}


- (void)clickSearchButton{
    
    HiddenBar;
    SearchContactsViewController * searchVC = [SearchContactsViewController new];
    
    searchVC.string = @"搜索联系人";
    
    [self.navigationController pushViewController:searchVC animated:YES];
    ShowBar;
}

#pragma mark - TableView 占位图
- (NSString *)xy_noDataViewMessage {
    
    return @"";
}

- (UIColor *)xy_noDataViewMessageColor {
    
    return [UIColor blackColor];
}

- (void)clickItemID:(NSString *)ID{

    UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                   message:@"确定不再关注此人？"
                                                            preferredStyle:UIAlertControllerStyleAlert];
    
    UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault
                                                          handler:^(UIAlertAction * action) {
                                                              
                                                              [self attentionPersonWith:ID];
                                                          }];
    UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                         handler:^(UIAlertAction * action) {
                                                             
                                                         }];
    
    [alert addAction:defaultAction];
    [alert addAction:cancelAction];
    [self presentViewController:alert animated:YES completion:nil];
}


- (void)attentionPersonWith:(NSString *)ID{
    
    [[ZRNetworkTool sharedTool] cancelAttentionUserUser_id:ID ResultWithBlock:^(BOOL success, id responseData) {
        
        if (success) {
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
//                                                                      [self.dataArray removeAllObjects];
                                                                      [self loadData];
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }else{
            
            UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                           message:responseData[@"message"]
                                                                    preferredStyle:UIAlertControllerStyleAlert];
            
            UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                  handler:^(UIAlertAction * action) {
                                                                      
                                                                  }];
            
            [alert addAction:defaultAction];
            [self presentViewController:alert animated:YES completion:nil];
        }
    }];
}


- (void)clickFansItemID:(NSString *)ID WithType:(NSString *)type{
    
    if ([type isEqualToString:@"cancel"]) {
        
        UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                       message:@"确定不再关注此人？"
                                                                preferredStyle:UIAlertControllerStyleAlert];
        
        UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault
                                                              handler:^(UIAlertAction * action) {
                                                                  
                                                                  [self attentionPersonWith:ID];
                                                              }];
        UIAlertAction* cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel
                                                             handler:^(UIAlertAction * action) {
                                                                 
                                                             }];
        
        [alert addAction:defaultAction];
        [alert addAction:cancelAction];
        [self presentViewController:alert animated:YES completion:nil];
    }else{
        
        [[ZRNetworkTool sharedTool] attentionUseroWithUser_id:ID ResultWithBlock:^(BOOL success, id responseData) {
            
            if (success) {
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
//                                                                          [self.dataArray removeAllObjects];
                                                                          [self loadData];
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }else{
                
                UIAlertController* alert = [UIAlertController alertControllerWithTitle:@""
                                                                               message:responseData[@"message"]
                                                                        preferredStyle:UIAlertControllerStyleAlert];
                
                UIAlertAction* defaultAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleCancel
                                                                      handler:^(UIAlertAction * action) {
                                                                          
                                                                      }];
                
                [alert addAction:defaultAction];
                [self presentViewController:alert animated:YES completion:nil];
            }
        }];
    }
    
}

- (void)onReceiveMessage:(JMSGMessage *)message error:(NSError *)error{
    
    [self updateData];
}

@end
